<?php

require_once 'PipesImpl/Visitor.php';

class Pipes_ModelList_Grid_RowBuilder implements PipesImpl_Visitor
{
    private $_document = null;
    private $_capture  = null;

    public function __construct(Pipes_Xml_Document $document, Pipes_Xml_Document $capture = null) {
        $this->_document = $document;
        $this->_capture = $capture;
    }

    public function visit(PipesImpl_Visitable $visitable) {
        $model = $visitable;
        $mainKey = "{$model->getName()}_id";

        $tr = $this->_document->createElement('tr');
        $this->_document->getElementsByTagName('tbody')->item(0)->appendChild($tr);

        $rowId = "row_{$model->getName()}_{$model->$mainKey}";
        
        $trId = $this->_document->createAttribute('id');
        $trId->nodeValue = $rowId;
        $tr->appendChild($trId);
        
        $propertyNames = array_merge(
            array_keys($model->getColumns()),
            $model->listRelationships()
        );
        foreach ($propertyNames as $property) {
            if (!is_null($this->_capture)) {
                $xpath = new Pipes_Xml_Xpath($this->_capture);
                //var_dump(htmlentities($this->_capture->saveXML()));
                $query = "//*[@pipes:for='{$property}']";
                $element = $xpath->query($query);
                if ($element->length > 0) {
                    $cell = $this->_document->importNode($element->item(0), true);
                    $tr->appendChild($cell);
                    // break out of this as we've done our job
                    continue;
                }
            }
            // if nothing else has already stopped this process, continue by creating
            // the default grid element
            $cell = $this->_buildCell($model, $property);
            if (!is_null($cell)) {
                $tr->appendChild($cell);
            }
        }
    }

    private function _buildCell($model, $property) {
        if (in_array($property, $model->listRelationships())) {
            // ignore relationships by default
            return;
        }
        $td = $this->_document->createElement('td');
        $td->nodeValue = $model->$property;
        $id = $this->_document->createAttribute('id');
        $id->nodeValue = "id_{$property}";
        $td->appendChild($id);
        if ($property == $model->idColumn()->name) {
            $hiddenAttribute = $this->_document->createAttribute('style');
            $hiddenAttribute->nodeValue = "display:none;";
            $td->appendChild($hiddenAttribute);
        }

        return $td;
    }
}
